package com.example.demo2.controller;

import com.example.demo2.dao.Departmentdao;
import com.example.demo2.dao.Productdao;
import com.example.demo2.pojo.Department;
import com.example.demo2.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

//商品管理
@Controller
public class ProdectController {
    //control层应该调用service层
    //这里还没写service层
    //先调用dao层
    @Autowired //注入
    Productdao productdao;

    @Autowired
    Departmentdao departmentdao;

    @RequestMapping("/Products")
    public String list(Model model){
        Collection<Product> products= productdao.getProducts();//获取所有商品信息
        model.addAttribute("pdts",products);//将商品信息放入model中
        return "Products/basic_table";
    }

    //添加商品
    @RequestMapping("/pdt")
    public String toAddproduct(Model model){
        //查出所有商品种类的信息
        Collection<Department> departments= departmentdao.getDepartments();
        model.addAttribute("departments",departments);//将商品种类信息放入model中
        return "Products/add";
    }

    //提交添加商品的表单
    @PostMapping("/pdt")
    public String Addproduct(Product product){
        //添加商品的操作
        productdao.save(product);//调用（dao层）底层业务方法
        return "redirect:/Products";//重定向到/Products页面
    }

    //跳转商品的修改页面
    @RequestMapping("/pdt/{id}")
    public String toUpdatePdt(@PathVariable("id") Integer id,Model model){
        //查出原来的数据
        Product product=Productdao.getProductById(id);
        model.addAttribute("pdt",product);

        //主要是为了查出所有商品种类的信息好进行遍历
        Collection<Department> departments= departmentdao.getDepartments();
        model.addAttribute("departments",departments);//将商品种类信息放入model中
        return "Products/update";
    }

    @PostMapping("/updatePdt")
    public String updataPdt(Product product){
        productdao.save(product);
        return "redirect:/Products";
    }

    //删除商品信息
    @GetMapping("/delpdt/{id}")
    public String deletePdt(@PathVariable("id") Integer id){
        productdao.deleteById(id);
        return "redirect:/Products";
    }
}
